package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"store/models"
)

type StoresControllers struct {
	beego.Controller
}

type Json struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *StoresControllers) Page() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("p", 1)
	size, _ := c.GetInt("s", 2)
	store, count, err := models.Page(page, size)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "分页失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		pageData := make(map[string]interface{})
		pageData["store"] = store
		pageData["count"] = count
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "分页成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}

func (c *StoresControllers) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	store, err := models.List(name)
	if err != nil {
		c.Data["json"] = Json{
			Code: 500,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Json{
			Code: 200,
			Msg:  "展示成功",
			Data: store,
		}
		c.ServeJSON()
	}
}
